package com.jiangwh.domain.security;

import java.security.MessageDigest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component("securityAuthenticationProvider")
public class SecurityAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	@Qualifier("userDetailsService")
	SecurityAuthenticationUserDetailService userDetailsService;

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		//TODO 查找相关信息
		String uploadPassWord = String.valueOf(authentication.getCredentials());
		System.out.println("上传的用户密码"+uploadPassWord);
		UserDetails userDetails = this.userDetailsService.loadUserByUsername(authentication.getName());
		//校验密码md5方式
		try {
			System.out.println("koala == "+userDetails.getPassword());
			authentication.getPrincipal();
			System.out.println("upload:"+authentication.getPrincipal());
			System.out.println("upload-p"+authentication.getCredentials());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update("sa@123".getBytes());
		} catch (Exception e) {
			throw new BadCredentialsException("加密算法异常。");
		}		
		
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
				userDetails, authentication.getCredentials(),
				userDetails.getAuthorities());
		System.out.println("返回信息:"+token);
		return token;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
	}
}
